<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import type { ElTable } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, RefreshRight, Plus, Delete } from '@element-plus/icons-vue'
import { DictModel } from './class/DictModel'
import { getDictList, changeDictStatus, deleteDict, batchDeleteDict } from '../../../http/index'
import addDictVue from './components/add.vue'

const ruleFormRef = ref<FormInstance>()
const multipleTableRef = ref<InstanceType<typeof ElTable>>()

// 表单查询条件
const form = reactive({
    dictId: '',
    dictType: '',
    dictName: '',
    dictKey: '',
    status: '',
    pageIndex: 1,
    pageSize: 10,
    total: 0
})

const rules = reactive<FormRules>({
    dictType: [{ required: false, message: '请输入字典类型', trigger: 'blur' }]
})

// 查询
const onSubmit = async (ruleFormRef: FormInstance | undefined) => {
    if (!ruleFormRef) return;
    await ruleFormRef.validate((valid) => {
        if (valid) {
            LoadTableData()
        }
    })
}

// 重置
const resetForm = (ruleFormRef: FormInstance | undefined) => {
    if (!ruleFormRef) return
    ruleFormRef.resetFields()
    form.pageIndex = 1
    LoadTableData()
}

// 新增弹窗控制
const addVisible = ref(false)
const info = ref()

const add = () => {
    info.value = null;
    addVisible.value = true;
}

// 关闭弹窗回调
const CloseAdd = () => {
    addVisible.value = false;
    info.value = undefined;
    LoadTableData();
}

// 编辑
const handleEdit = (index: number, row: DictModel) => {
    info.value = JSON.stringify(row)
    addVisible.value = true
}

// 单个删除
const handleDelete = async (index: number, row: DictModel) => {
    ElMessageBox.confirm(
        `确定要删除字典【${row.dictName}】吗？`,
        '删除确认',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        const res = await deleteDict(row.dictId) as any
        if (res.status) {
            ElMessage({
                message: '删除成功！',
                type: 'success',
            })
            LoadTableData()
        }
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消删除'
        })
    })
}

// 批量删除
const batchDelete = async () => {
    const selectedRows = multipleTableRef.value?.getSelectionRows()
    if (!selectedRows || selectedRows.length === 0) {
        ElMessage({
            message: '请选择要删除的字典',
            type: 'warning'
        })
        return
    }

    ElMessageBox.confirm(
        `确定要删除选中的${selectedRows.length}个字典吗？`,
        '批量删除确认',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        const ids = selectedRows.map(row => row.dictId).join(',')
        const res = await batchDeleteDict(ids) as any
        if (res.status) {
            ElMessage({
                message: '批量删除成功！',
                type: 'success',
            })
            LoadTableData()
        }
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消删除'
        })
    })
}

// 表格数据
const tableData = ref<Array<DictModel>>()

// 加载表格数据
const LoadTableData = async () => {
    const params = {
        dictId: form.dictId || '',
        dictType: form.dictType || '',
        dictName: form.dictName || '',
        dictKey: form.dictKey || '',
        status: form.status || '',
        pageIndex: form.pageIndex,
        pageSize: form.pageSize
    }
    const res = await getDictList(params) as any
    tableData.value = res.data.list as DictModel[]
    form.total = res.data.total
}

// 页面加载时初始化数据
onMounted(async () => {
    LoadTableData()
})

// 分页切换
const handleCurrentChange = (val: number) => {
    form.pageIndex = val
    LoadTableData()
}

// 切换字典状态
const toggleStatus = async (row: DictModel) => {
    const newStatus = row.status === 1 ? 0 : 1
    const statusText = newStatus === 1 ? '启用' : '禁用'
    const res = await changeDictStatus(row.dictId, newStatus) as any
    
    if (res.status) {
        ElMessage({
            message: `字典【${row.dictName}】${statusText}成功！`,
            type: 'success',
        })
        row.status = newStatus
    } else {
        ElMessage({
            message: `字典【${row.dictName}】${statusText}失败！`,
            type: 'error'
        })
    }
}
</script>

<template>
    <el-card class="box-card">
        <template #header>
            <div class="card-header">
                <el-form :inline="true" :model="form" class="demo-form-inline" :rules="rules" ref="ruleFormRef">
                    <el-form-item label="字典ID" prop="dictId">
                        <el-input v-model="form.dictId" placeholder="请输入字典ID" style="width: 120px;" />
                    </el-form-item>
                    <el-form-item label="字典类型" prop="dictType">
                        <el-input v-model="form.dictType" placeholder="请输入字典类型" style="width: 150px;" />
                    </el-form-item>
                    <el-form-item label="字典名称" prop="dictName">
                        <el-input v-model="form.dictName" placeholder="请输入字典名称" style="width: 150px;" />
                    </el-form-item>
                    <el-form-item label="字典键值" prop="dictKey">
                        <el-input v-model="form.dictKey" placeholder="请输入字典键" style="width: 150px;" />
                    </el-form-item>
                    <el-form-item label="状态">
                        <el-select v-model="form.status" placeholder="全部" style="width: 120px;">
                            <el-option label="启用" value="1" />
                            <el-option label="禁用" value="0" />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="onSubmit(ruleFormRef)">
                            <el-icon><Search /></el-icon>查询
                        </el-button>
                        <el-button @click="resetForm(ruleFormRef)">
                            <el-icon><RefreshRight /></el-icon>重置
                        </el-button>
                    </el-form-item>
                </el-form>
                <p>
                    <el-button type="primary" @click="add">
                        <el-icon><Plus /></el-icon>新增字典
                    </el-button>
                    <el-button type="danger" @click="batchDelete">
                        <el-icon><Delete /></el-icon>批量删除
                    </el-button>
                </p>
            </div>
        </template>

        <el-table 
            :data="tableData" 
            style="width: 100%" 
            ref="multipleTableRef"
            border
        >
            <el-table-column type="selection" width="55" />
            <el-table-column label="字典ID" prop="dictId" width="80" />
            <el-table-column label="字典类型" prop="dictType" width="120" />
            <el-table-column label="字典名称" prop="dictName" width="150" />
            <el-table-column label="字典键" prop="dictKey" width="120" />
            <el-table-column label="字典值" prop="dictValue" width="150" />
            <el-table-column label="排序" prop="sort" width="80" />
            <el-table-column label="状态">
                <template #default="scope">
                    <el-switch 
                        v-model="scope.row.status" 
                        :active-value="1" 
                        :inactive-value="0"
                        @change="toggleStatus(scope.row)"
                        active-text="启用"
                        inactive-text="禁用"
                    />
                </template>
            </el-table-column>
            <el-table-column label="备注" prop="remark" />
            <el-table-column label="创建时间" prop="createTime" width="180" />
            <el-table-column label="操作" align="right" width="200">
                <template #default="scope">
                    <el-button size="small" type="primary" @click="handleEdit(scope.$index, scope.row)">
                        编辑
                    </el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination 
            background 
            layout="total, prev, pager, next, jumper" 
            :total="form.total"
            :page-size="form.pageSize"
            :current-page="form.pageIndex"
            @current-change="handleCurrentChange"
            style="margin-top: 20px; text-align: right;"
        />
    </el-card>

    <addDictVue 
        :addVisible="addVisible" 
        :info="info" 
        @CloseAdd="CloseAdd"
    ></addDictVue>
</template>

<style lang="scss" scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
}

.el-pagination {
    margin-top: 20px;
}
</style>